/**
 * 请求工具 - 配置axios实例和后端IP
 */

import axios from 'axios'

// 后端服务器地址配置
const BASE_URL = 'http://localhost:8080'

// 创建axios实例
const request = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器 - 添加token
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器 - 处理token过期
request.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      localStorage.removeItem('token')
      // 可以在这里触发跳转到登录页
      window.dispatchEvent(new CustomEvent('auth-expired'))
    }
    return Promise.reject(error)
  },
)

export default request
